package com.study.config;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;

/**
 * @Author: MI
 * @Date: 2021/8/21/13:00
 * @Description:
 */
//整合shiro框架 配置
@Configuration
public class ShiroConfig {

    //1 创建shiroFilter 负责 拦截所有的请求
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager webSecurityManager) {
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        //设置安全管理器
        bean.setSecurityManager(webSecurityManager);

        //配置受限资源
        //配置系统公共资源
        HashMap<String, String> map = new HashMap<>();
        map.put("/**", "authc");


        map.put("/user/login", "anon");
        map.put("/regist.jsp", "anon");
        map.put("/user/**", "anon");

        //默认认证界面路径
        bean.setLoginUrl("/login.jsp");
        bean.setFilterChainDefinitionMap(map);

        return bean;
    }

    // 2 创建安全管理器
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(Realm realm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //给安全管理器设置 realm
        securityManager.setRealm(realm);
        return securityManager;
    }

    // 3 创建自定义 Realm
    @Bean
    public Realm getRealm() {

        CustomerRealm realm = new CustomerRealm();
        //修改凭证校验匹配器
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        //设置MD5 加密算法
        matcher.setHashAlgorithmName("MD5");
        // 设置 散列次数
        matcher.setHashIterations(1024);
        realm.setCredentialsMatcher(matcher);
        return realm;
    }
}
